package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.UserService;
import com.itheima.bean.R;
import com.itheima.bean.User;

import com.itheima.config.ThreadLocalConfig;
import com.itheima.exception.CustomException;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/loginout")
    public  R logout(HttpSession session){
        try {
            session.invalidate();


            return R.success("退出成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("退出失败！");
        }
    }


    @GetMapping("/login/{params}")
    public R login(@PathVariable String params ,HttpSession session){
        Map<String,Object> map = JSON.parseObject(params, Map.class);
        String phone = (String)map.get("phone");
        String code = (String)map.get("code");
        if (phone==null){
            throw new CustomException("电话号码不能为空！");
        }
        String code1 = (String)session.getAttribute(phone);
        if (code1==null){
            throw new CustomException("验证码不能为空！");
        }
        if (code1.equalsIgnoreCase(code)){
            System.out.println("============================dfghjkl");
            User user = new User();
            user.setPhone(phone);
            user.setStatus(1);
          User user1 = userService.findByPhone(phone);

          if (user1==null){
              userService.add(user);

              session.setAttribute("user",user);
          }else {
              session.setAttribute("user",user1);

          }


                return R.success("登陆成功！");

        }
        return R.error("登陆失败！");
    }

    @PostMapping("/sms")
    public R sentCode(@RequestBody User user, HttpSession session){
        try {
            String phone = user.getPhone();
//        获得验证码
            String code = ValidateCodeUtils.generateValidateCode4String(6);
            System.out.println("============"+code);
//        发送短信
//            SMSUtils.sendMessage("瑞吉外卖","SMS-10008",phone,code);
//        保存手机和验证码

            session.setAttribute(phone,code);
            return R.success("验证码发送成功！");
        } catch (CustomException e) {
            e.printStackTrace();
            return R.error("验证码发送失败！");
        }
    }
}
